const fs = require("fs");
const path = require("path");
const koa = require("koa");
const complilerSFC = require("@vue/compiler-sfc");

const app = new koa();

app.use(async (ctx, next) => {
  if (ctx.path === "/") {
    ctx.type = "text/html";
    ctx.body = fs.readFileSync("./index.html", "utf-8");
  } else if (ctx.path.endsWith(".js") || ctx.path.endsWith(".ts")) {
    const p = path.join(__dirname, ctx.path);
    ctx.type = "application/javascript";
    // ctx.body = fs.readFileSync(p, "utf-8");

    ctx.body = rewriteImport(fs.readFileSync(p, "utf8"));
  } else if (ctx.path.startsWith("/@modules/")) {
    const moduleName = ctx.path.replace("/@modules/", ""); // vue

    // 指向 node_modules 里的目录
    const prefix = path.join(__dirname, "./node_modules", moduleName);

    // 获取 package.json 的 module 字段（找到对应打好的包的入口）
    const module = require(prefix + "/package.json").module;

    // 获取 js 文件的完整路径
    const filePath = path.join(prefix, module);

    const ret = fs.readFileSync(filePath, "utf-8");

    ctx.type = "application/javascript";
    ctx.body = rewriteImport(ret);
  } else if (ctx.path.endsWith(".vue")) {
    // 读取 vue 文件
    const p = path.join(__dirname, ctx.path);
    // 通过 vue 的编译库将用 parse 解析成 sfc 对象 （SFCParseResult）
    const ret = complilerSFC.parse(fs.readFileSync(p, "utf-8"));
    // 将其中的 template 进行进一步的转换
    const template = complilerSFC.compileTemplate({
      id: "123",
      filename: "foo.vue",
      source: ret.descriptor.template.content,
    });
    const { code } = template;

    // todo：how to deal with the code to render template
    ctx.type = "application/javascript";
    ctx.body = rewriteImport(code);
  }
});

function rewriteImport(content) {
  return content.replace(/ from ['"](.*)['"]/g, function (s1, s2) {
    if (s2.startsWith("./") || s2.startsWith("/") || s2.startsWith("../")) {
      return s1;
    } else {
      //裸模块，替换
      return `from '/@modules/${s2}'`;
    }
  });
}

app.listen(3000, () => {
  console.log("server is running at http://localhost:3000");
});
